//
//  MYGUploadManager+DataManager.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/15.
//

import UIKit

extension MYGUploadManager {
    private static let filePath = "MYGUploadManager"

     func saveModels(_ model:MYGUploadModel) {
        let path = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!).appendingPathComponent("MYGUploadModels")
        print(path ?? "")
        do{
        let userData = try? NSKeyedArchiver.archivedData(withRootObject: MYGUploadManager.shared.uploadedArray, requiringSecureCoding: false)

        try userData?.write(to: path!)

        print("Saved")

        }catch let error as NSError{

        print("\(error)")
        }
    }
    
//    static func adddModel(_ model: MYGUploadModel) {
//        removeUser()
//        let path = filePath + "/" + model.name
//        let file_path = (NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent(path)
//        guard let data = model.toJSON()?.jsonData() else {
//            return
//        }
//        do {
//            try data.write(to: URL(fileURLWithPath: file_path))
//        } catch {
//          
//        }
//    }
    
     func getDownloadModels() -> [MYGUploadModel]? {
        guard  let file_path = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!).appendingPathComponent("MYGUploadModels") else {return nil}

        do {
            let data = try Data(contentsOf: file_path)

            let unarchivedData = try NSKeyedUnarchiver.unarchivedObject(ofClasses: [NSArray.self,MYGUploadModel.self], from: data) as? [MYGUploadModel]
            return unarchivedData
        } catch {
            print("数据获取失败")
            return nil
        }
    }

    static func removeUser() {
        let file_path = (NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true).first! as NSString).appendingPathComponent(filePath)
        do {
           try FileManager.default.removeItem(atPath: file_path)
        } catch {
            print("用户数据删除失败")
        }
    }
}
